package org.huhuiyu.easyui.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.huhuiyu.easyui.enity.Dtreemenu;
import org.huhuiyu.easyui.enity.JQueryMenu;
import org.huhuiyu.easyui.service.DtreemenuService;
import com.opensymphony.xwork2.Action;

public class MenuAction {
	private Logger logger = Logger.getLogger(MenuAction.class);
	private DtreemenuService dtreemenuService;

	public DtreemenuService getDtreemenuService() {
		return dtreemenuService;
	}

	public void setDtreemenuService(DtreemenuService dtreemenuService) {
		this.dtreemenuService = dtreemenuService;
	}

	public String queryAllMenu() throws Exception {
		logger.debug(dtreemenuService);
		List<Dtreemenu> menus = dtreemenuService.queryAllDtreemenu();
		logger.debug(menus);
		JsonActionUtil util = JsonActionUtil.getSuccessJson("menus",
				processMenus(menus, null));
		util.write();
		return Action.NONE;
	}

	private List<JQueryMenu> processMenus(List<Dtreemenu> menus, Integer parent) {
		String root = ServletActionContext.getServletContext().getContextPath();
		ArrayList<JQueryMenu> list = new ArrayList<JQueryMenu>();
		for (Dtreemenu dtreemenu : menus) {
			logger.debug(dtreemenu);
			if (dtreemenu.getParent() == parent) {
				JQueryMenu m = new JQueryMenu();
				m.setId(dtreemenu.getMid());
				m.setText(dtreemenu.getName());
				if (dtreemenu.getUrl() != null
						&& !dtreemenu.getUrl().trim().equals("")) {
					m.getAttributes().put("url", root + dtreemenu.getUrl());
				}
				m.setChildren(processMenus(menus, dtreemenu.getMid()));
				list.add(m);
			}
		}
		return list;
	}

}
